package com.kehongborui.empmanagesys.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-25
 */
public class ImageCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/jpeg");  //设置输出类型
        // 1.获取图片对象
        BufferedImage image = new BufferedImage(230, 60, BufferedImage.TYPE_INT_RGB);
        // 获取图片对象的画笔
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 230, 60);
        graphics.setColor(Color.BLACK);
        String letter = "ABCD1234567890abcd";
        // 获取随机字符
        char[] chars = new char[4];
        for (int index = 0; index < chars.length; index++) {
            chars[index] = letter.charAt((int)(Math.random() * letter.length()));
        }

        String code = new String(chars);
        // 将验证码放到session，在其他要用到的地方，再冲session获取出来就行了
        req.getSession().setAttribute("code", code);

        graphics.drawString(code, 20, 30);
        graphics.drawLine(0, 2, 4,49);
        graphics.drawLine(0, 12, 4,49);

        // 获取输出流
        OutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "JPG", outputStream);
        outputStream.flush();
    }
}
